import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../entities/User.entity';
import * as bcrypt from 'bcryptjs';
import { compareSync, hashSync } from 'bcryptjs';
import { UpdateUserInfoDto } from '../dto/update-userinfo.dto';
import { UpdatePasswordDto } from '../dto/update-password.dto';
import { UpdateAvatarDto } from '../dto/update-avatar.dto';

@Injectable()
export class UserInfoService {
  constructor(
    @InjectRepository(User)
    private readonly userInfoRepository: Repository<User>,
  ) {}

  async getUserInfo(userId: number): Promise<User|null> {
    return this.userInfoRepository.findOne({
      where:{
        id:userId
      }
    });
  }

  async updateUserInfo(userId: number, updateUserInfoDto: UpdateUserInfoDto): Promise<User> {
    const userInfo = await this.userInfoRepository.findOne({
      where:{
        id:userId
      }
    });
    if (!userInfo) {
      throw new Error('User not found');
    }
    this.userInfoRepository.merge(userInfo, updateUserInfoDto);
    return await this.userInfoRepository.save(userInfo);
  }

  async updatePassword(userId: number, updatePasswordDto: UpdatePasswordDto): Promise<string> {
    const userInfo = await this.userInfoRepository.findOne({
      where:{
        id:userId
      }
    });
    console.log('userInfo',userInfo);
    
    if (!userInfo) {
      throw new Error('User not found');
    }
    const { oldPwd, newPwd } = updatePasswordDto;
    
    // 验证旧密码是否正确
    const isOldPasswordCorrect = await bcrypt.compare(oldPwd, userInfo.password);
    if (!isOldPasswordCorrect) {
      throw new Error('Old password is incorrect');
    }

    // 加密新密码并保存
    const hashedNewPwd = await bcrypt.hash(newPwd, 10);
    userInfo.password = hashedNewPwd;
    await this.userInfoRepository.save(userInfo);
    return "修改成功"

  }

  async updateAvatar(userId: number, updateAvatarDto: UpdateAvatarDto): Promise<void> {
    const userInfo = await this.userInfoRepository.findOne({
      where:{
        id:userId
      }
    });
    if (!userInfo) {
      throw new Error('User not found');
    }
    // userInfo.avatar = updateAvatarDto.avatar;
    await this.userInfoRepository.save(userInfo);
  }
}
